<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="renderer" content="webkit">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>视频</title>
    <style>
        html, body { padding: 0; margin: 0; width: 100%; height: 100%;}
        #container {
            width: 100%;
            height: 100%;
        }
    </style>
</head>
  <body>
    <button id="btn">Call</button>
    <video id="localVideo" playsinline autoplay muted></video>
    <video id="remoteVideo" playsinline autoplay></video>
    <div id="container"></div>
    <script type="text/javascript" src="/socket.io/socket.io.js"></script>
    <script type="text/javascript">
        const btn = document.getElementById('btn');
        const localVideo = document.getElementById('localVideo');
        const remoteVideo = document.getElementById('remoteVideo');
        const socket = io();
        let peer1 = new RTCPeerConnection({});
        let peer2 = null;

        async function run() {
          const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
          localVideo.srcObject = stream;
          localStream = stream;
          
          for (const track of localStream.getTracks()) {
            peer1.addTrack(track, localStream);
          }
          peer1.onicecandidate = (e) => {
            socket.emit("message", JSON.stringify({
              type: 'perr1Ice',
              peer: peer1,
              data: e.candidate
            }))
          }
          const offer = await peer1.createOffer({
            offerToReceiveAudio: 1,
            offerToReceiveVideo: 1
          });
          await peer1.setLocalDescription(offer);
          socket.emit("message", JSON.stringify({
            type: 'offer',
            data: offer
          }))

          if(peer2) {
            peer2.ontrack = (e) => {
              console.log(e)
            }
          }
        }
        
        socket.on("message", async (msg) => {
          msg = JSON.parse(msg);
          if(msg.type === 'perr1Ice') {
            peer1.addIceCandidate(msg.data);
            console.log(msg)
            peer2 = msg.peer
            peer2.onicecandidate = (e) => {
              socket.emit("message", JSON.stringify({
                type: 'perr2Ice',
                peer: peer1,
                data: e.candidate
              }))
            }
            const answer = await peer2.createAnswer();
            await peer2.setLocalDescription(answer);
            socket.emit("message", JSON.stringify({
              type: 'answer',
              data: offer
            }))
          }
          if(msg.type === 'perr2Ice') {
            if(peer2) peer2.addIceCandidate(msg.data)
          }
          if(msg.type === 'offer') {
            if(peer2) await peer2.setRemoteDescription(offer);
          }
          if(msg.type === 'answer') {
            await peer1.setRemoteDescription(offer);
          }
        })

        run()




        // let peer2 = null;
        // btn.onclick = async () => {
        //   peer1 = new RTCPeerConnection({});
        //   const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
        //   localVideo.srcObject = stream;
        //   localStream = stream;
          
        //   for (const track of localStream.getTracks()) {
        //     peer1.addTrack(track, localStream);
        //   }
        //   peer1.onicecandidate = (e) => {
        //     socket.emit("message", JSON.stringify({
        //       type: 'perr1Ice',
        //       userId: 1,
        //       data: e.candidate
        //     }))
        //   }
        //   const offer = await peer1.createOffer({
        //     offerToReceiveAudio: 1,
        //     offerToReceiveVideo: 1
        //   });
        //   await peer1.setLocalDescription(offer);
        //   // call();
        // }

        // async function call() {
        //   peer2 = new RTCPeerConnection({});
        //   peer2.onicecandidate = (e) => {
        //     socket.emit("message", JSON.stringify({
        //       type: 'perr2Ice',
        //       data: e.candidate
        //     }))
        //   }
        //   peer2.ontrack = (e) => {
        //     const remoteVideo = document.getElementById('remoteVideo');
        //     if (remoteVideo.srcObject !== e.streams[0]) {
        //       remoteVideo.srcObject = e.streams[0];
        //     }
        //   }
        // }

        // socket.on("message", async (msg) => {
        //   msg = JSON.parse(msg);
        //   console.log(msg)
        //   // if(msg.type === 'perr1Ice') {
        //   //   peer2.addIceCandidate(msg.data)
        //   // }
        //   // if(msg.type === 'perr2Ice') {
        //   //   peer1.addIceCandidate(msg.data);
        //   //   const offer = await peer1.createOffer({
        //   //     offerToReceiveAudio: 1,
        //   //     offerToReceiveVideo: 1
        //   //   });
        //   //   await peer1.setLocalDescription(offer);
        //   //   socket.emit("message", JSON.stringify({
        //   //     type: 'offer',
        //   //     data: offer
        //   //   }))
        //   // }
        //   // if(msg.type === 'offer') {
        //   //   peer2.setRemoteDescription(msg.data);
        //   //   const answer = await peer2.createAnswer();
        //   //   socket.emit("message", JSON.stringify({
        //   //     type: 'answer',
        //   //     data: answer
        //   //   }))
        //   // }
        //   // if(msg.type === 'answer') {
        //   //   await peer1.setRemoteDescription(msg.data);
        //   //   await peer2.setLocalDescription(msg.data);
        //   // }
        // });
    </script>
  </body>
</html>
